<template>
	<view class="container">
		<!-- 页面标题 -->
		<view class="page-title">角色信息管理</view>

		<!-- 查询区域 -->
		<view class="search-container">

			<view class="search-item">
				<text class="label">角色:</text>
				<picker class="picker" @change="onRoleChange" :value="selectedRoleIndex" :range="roleOptions"
					:range-key="'label'">
					<view class="picker-view">
						{{ selectedRole !== null ? roleOptions.find(item => item.value === selectedRole)?.label : '集团' }}
					</view>
				</picker>
			</view>

			<view class="search-item">
				<text class="label">用户名:</text>
				<input class="search-input" v-model="userName" placeholder="请输入用户名" />
			</view>

			<view class="search-item">
				<text class="label">应用ID:</text>
				<input class="search-input" disabled="true" v-model="searchAppId" placeholder="请输入应用ID" />
			</view>

			<button class="search-btn" @click="handleSearch">查询</button>
			<button class="reset-btn" @click="resetSearch">重置</button>
			<button class="add-btn" @click="showAddDialog">新增</button>
		</view>

		<!-- 列表区域 -->
		<view class="list-container">
			<!-- 列表表头 -->
			<view class="list-header">
				<view class="list-item username-column">用户名</view>
				<view class="list-item role-column">角色</view>
				<view class="list-item appid-column">应用ID</view>
				<view class="list-item store-column">门店ID</view>
				<view class="list-item operation-column">操作</view>
			</view>

			<!-- 列表内容 -->
			<view class="list-body">
				<view class="list-row" v-for="(item, index) in tableData" :key="item.id"
					:class="{ 'row-odd': index % 2 === 0 }">
					<view class="list-item username-column">{{ item.userName || '-' }}</view>
					<view class="list-item role-column">{{ getRoleLabel(item.role) }}</view>
					<view class="list-item appid-column">{{ item.appId }}</view>
					<view class="list-item store-column">
						{{ item.pmsId ? getStoreName(item.pmsId) : '-' }}
					</view>
					<view class="list-item operation-column">
						<button class="edit-btn" @click="handleEdit(item.id)">修改</button>
						<button class="delete-btn" @click="handleDelete(item.id)">删除</button>
					</view>
				</view>

				<!-- 空状态 -->
				<view class="empty-state" v-if="tableData.length === 0 && !loading">
					<image src="/static/images/empty.png" class="empty-img" mode="widthFix"></image>
					<text class="empty-text">暂无数据</text>
				</view>

				<!-- 加载状态 -->
				<view class="loading-state" v-if="loading">
					<u-loading-icon color="#1677ff" size="24"></u-loading-icon>
					<text class="loading-text">加载中...</text>
				</view>
			</view>
		</view>

		<!-- 分页区域 -->
		<view class="pagination" v-if="total > 0 && !loading">
			<button class="page-btn" @click="changePage(1)" :disabled="currentPage === 1">
				首页
			</button>
			<button class="page-btn" @click="changePage(currentPage - 1)" :disabled="currentPage === 1">
				上一页
			</button>
			<view class="page-info">
				第 {{ currentPage }} 页 / 共 {{ totalPages }} 页
			</view>
			<button class="page-btn" @click="changePage(currentPage + 1)" :disabled="currentPage === totalPages">
				下一页
			</button>
			<button class="page-btn" @click="changePage(totalPages)" :disabled="currentPage === totalPages">
				末页
			</button>
		</view>

		<!-- 新增/编辑弹出框 -->
		<view class="modal-overlay" v-if="dialogVisible" @click="dialogVisible = false">
			<view class="modal-container" @click.stop>
				<view class="modal-header">
					<text class="modal-title">{{ isEdit ? '修改角色信息' : '新增角色信息' }}</text>
					<button class="modal-close" @click="dialogVisible = false">×</button>
				</view>

				<view class="modal-body">
					<view class="form-item">
						<text class="form-label">用户ID:</text>
						<input class="form-input" v-model="formData.userId" placeholder="请输入用户ID" :disabled="isEdit" />
					</view>
					<view class="form-item">
						<text class="form-label">用户名:</text>
						<input class="form-input" v-model="formData.userName" placeholder="请输入用户名" />
					</view>

					<view class="form-item">
						<text class="form-label">角色:</text>
						<picker class="form-picker" @change="onFormRoleChange" :value="formRoleIndex"
							:range="formRoleOptions" :range-key="'label'">
							<view class="picker-view">
								{{ formData.role !== null ? roleOptions.find(item => item.value === formData.role)?.label : '请选择角色' }}
							</view>
						</picker>
					</view>

					<view class="form-item">
						<text class="form-label">门店ID:</text>
						<picker class="form-picker" @change="onStoreChange" :value="selectedStoreIndex"
							:range="storeOptions" :range-key="'label'">
							<view class="picker-view">
								{{ formData.pmsId ? getStoreName(formData.pmsId) : '请选择门店' }}
							</view>
						</picker>
					</view>

					<view class="form-item">
						<text class="form-label">应用ID:</text>
						<input class="form-input" disabled="true" v-model="formData.appId" placeholder="请输入应用ID" />
					</view>
				</view>

				<view class="modal-footer">
					<button class="clear-btn" @click="clearForm">清空</button>
					<button class="cancel-btn" @click="dialogVisible = false">取消</button>
					<button class="confirm-btn" @click="submitForm">{{ isEdit ? '更新' : '保存' }}</button>
				</view>
			</view>
		</view>

		<!-- 删除确认弹窗 -->
		<view class="modal-overlay" v-if="deleteDialogVisible" @click="deleteDialogVisible = false">
			<view class="delete-modal" @click.stop>
				<view class="delete-title">确认删除</view>
				<view class="delete-content">确定要删除这条数据吗？此操作不可撤销。</view>
				<view class="delete-footer">
					<button class="delete-cancel" @click="deleteDialogVisible = false">取消</button>
					<button class="delete-confirm" @click="confirmDelete">删除</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 表格数据
				tableData: [],
				total: 0,
				currentPage: 1,
				pageSize: 10,
				loading: false,

				// API基础地址
				baseUrl: 'http://ziyan.xshhotels.cn:8981',

				// 查询条件
				selectedRole: null,
				searchAppId: '1000157', // 新增AppId查询条件
				roleOptions: [{
						value: 6,
						label: '全部'
					},
					{
						value: 0,
						label: '集团'
					},
					{
						value: 1,
						label: '华北'
					},
					{
						value: 2,
						label: '华中'
					},
					{
						value: 3,
						label: '苏沪'
					},
					{
						value: 4,
						label: '杭州'
					},
					{
						value: 5,
						label: '门店'
					}
				],
				storeOptions: [{
						value: "xshqs01",
						label: "北京曲水"
					},
					{
						value: "xshqs02",
						label: "武汉曲水1店"
					},
					{
						value: "xshqs04",
						label: "武汉曲水2店"
					},
					{
						value: "xshqs03",
						label: "杭州曲水"
					},
					{
						value: "xshqs05",
						label: "苏州曲水"
					},
					{
						value: "xshqs06",
						label: "上海曲水"
					},
					{
						value: "xshqs07",
						label: "郑州曲水"
					},
					{
						value: "xshsg01",
						label: "上海水裹1店"
					},
					{
						value: "xshsg02",
						label: "上海水裹2店"
					},
					{
						value: "xshsg03",
						label: "北京水裹"
					},
					{
						value: "xshsg04",
						label: "北京水裹加"
					},
					{
						value: "xshsg05",
						label: "杭州水裹1店"
					},
					{
						value: "xshsg06",
						label: "杭州水裹2店"
					},
					{
						value: "xshsg07",
						label: "武汉水裹"
					},
					{
						value: "xshsg08",
						label: "常州水裹"
					},
					{
						value: "xshsg09",
						label: "深圳水裹"
					}
				],

				// 弹窗相关
				dialogVisible: false, // 控制新增/编辑弹出框显示
				isEdit: false,
				deleteDialogVisible: false, // 控制删除确认框显示
				currentId: null,

				// 表单数据
				formData: {
					id: '',
					appId: '1000157',
					userId: '',
					userName: '',
					role: null,
					pmsId: '',
					createdOn: '',
					modifiedOn: ''
				}
			};
		},

		computed: {
			formRoleOptions() {
				return this.roleOptions.filter(item => item.value !== 6);
			},
			formRoleIndex() {
				return this.formRoleOptions.findIndex(item => item.value === this.formData.role);
			},
			// 总页数
			totalPages() {
				return Math.ceil(this.total / this.pageSize);
			},

			// 选中的角色索引
			selectedRoleIndex() {
				return this.roleOptions.findIndex(item => item.value === this.selectedRole);
			},
			selectedStoreIndex() {
				return this.storeOptions.findIndex(item => item.value === this.formData.pmsId);
			}
		},

		onLoad() {
			// 页面加载时获取数据
			this.getListData();
		},

		methods: {
			// 封装uni.request
			request(options) {
				return new Promise((resolve, reject) => {
					uni.request({
						url: this.baseUrl + options.url,
						method: options.method || 'GET',
						data: options.data || {},
						header: {
							'Content-Type': options.method === 'POST' ? 'application/json' :
								'application/x-www-form-urlencoded'
						},
						success: (res) => {
							if (res.statusCode === 200) {
								resolve(res.data);
							} else {
								reject(new Error(`请求失败，状态码: ${res.statusCode}`));
							}
						},
						fail: (err) => {
							reject(err);
						}
					});
				});
			},

			// 获取列表数据
			async getListData() {
				if (this.loading) return;

				this.loading = true;
				try {
					// 构建查询参数
					const params = new URLSearchParams();
					if (this.userName) {
						params.append('userName', this.userName);
					}
					if (this.selectedRole !== null && this.selectedRole !== undefined) {
						if (this.selectedRole != 6) {
							params.append('Role', this.selectedRole);
						}
					} else {
						params.append('Role', 0);
					}
					// 添加AppId查询参数
					if (this.searchAppId) {
						params.append('AppId', this.searchAppId);
					}
					params.append('PageSize', this.pageSize);
					params.append('PageIndex', this.currentPage);

					const res = await this.request({
						url: `/api/CheckInfoRole/Paging?${params.toString()}`
					});

					if (res.success && res.code === 200) {
						this.tableData = res.data.rows || [];
						this.total = res.data.total || 0;
					} else {
						uni.showToast({
							title: res.msg || '获取数据失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('获取数据失败:', error);
					uni.showToast({
						title: '网络错误，请稍后重试',
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
			},

			// 处理搜索
			handleSearch() {
				this.currentPage = 1; // 重置到第一页
				this.getListData();
			},

			// 重置搜索条件
			resetSearch() {
				this.selectedRole = null;
				this.searchAppId = '1000157'; // 重置AppId查询条件
				this.userName = '';
				this.currentPage = 1;
				this.getListData();
			},

			// 角色选择变化
			onRoleChange(e) {
				const index = e.detail.value;
				this.selectedRole = this.roleOptions[index]?.value || null;
			},

			// 门店选择变化
			onStoreChange(e) {
				const index = e.detail.value;
				this.formData.pmsId = this.storeOptions[index]?.value || '';
			},

			// 表单角色选择变化
			onFormRoleChange(e) {
				const index = e.detail.value;
				if (this.formRoleOptions[index]?.value === 0) {
					this.formData.role = 0;
				} else
					this.formData.role = this.formRoleOptions[index]?.value || null;
			},

			// 切换页码
			changePage(page) {
				if (page < 1 || page > this.totalPages) return;
				this.currentPage = page;
				this.getListData();
			},

			// 显示新增弹出框
			showAddDialog() {
				this.isEdit = false;
				this.clearForm();
				this.dialogVisible = true;
			},

			// 清空表单
			clearForm() {
				this.formData = {
					id: '',
					appId: '1000157',
					userId: '',
					userName: '', // 清空用户名
					role: null,
					pmsId: '',
					createdOn: '',
					modifiedOn: ''
				};
			},

			// 处理编辑
			async handleEdit(id) {
				this.loading = true;
				try {
					const res = await this.request({
						url: `/api/CheckInfoRole/Get?Id=${id}`
					});

					if (res.success && res.code === 200) {
						this.isEdit = true;
						this.currentId = id;
						this.formData = {
							...res.data
						};
						this.dialogVisible = true;
					} else {
						uni.showToast({
							title: res.msg || '获取详情失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('获取详情失败:', error);
					uni.showToast({
						title: '网络错误，请稍后重试',
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
			},

			// 处理删除
			handleDelete(id) {
				this.currentId = id;
				this.deleteDialogVisible = true;
			},

			// 确认删除
			async confirmDelete() {
				if (!this.currentId) return;

				this.loading = true;
				try {
					const res = await this.request({
						url: `/api/CheckInfoRole/Delete?Id=${this.currentId}`
					});

					if (res.success && res.code === 200) {
						uni.showToast({
							title: '删除成功',
							icon: 'success'
						});
						this.deleteDialogVisible = false;
						this.getListData();
					} else {
						uni.showToast({
							title: res.msg || '删除失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('删除失败:', error);
					uni.showToast({
						title: '网络错误，请稍后重试',
						icon: 'none'
					});
				} finally {
					this.loading = false;
					this.currentId = null;
				}
			},

			// 提交表单
			async submitForm() {
				// 简单验证
				if (!this.formData.userId) {
					return uni.showToast({
						title: '请输入用户ID',
						icon: 'none'
					});
				}

				if (!this.formData.userName) { // 验证用户名
					return uni.showToast({
						title: '请输入用户名',
						icon: 'none'
					});
				}

				if (this.formData.role === null) {
					return uni.showToast({
						title: '请选择角色',
						icon: 'none'
					});
				}

				if (!this.formData.appId) {
					return uni.showToast({
						title: '请输入应用ID',
						icon: 'none'
					});
				}

				this.loading = true;
				try {
					// 处理日期格式
					if (!this.isEdit) {
						this.formData.createdOn = new Date().toISOString();
						this.formData.modifiedOn = '0001-01-01T00:00:00';
					} else {
						this.formData.modifiedOn = new Date().toISOString();
					}

					const res = await this.request({
						url: '/api/CheckInfoRole/Save',
						method: 'POST',
						data: this.formData
					});

					if (res.success && res.code === 200) {
						uni.showToast({
							title: this.isEdit ? '更新成功' : '新增成功',
							icon: 'success'
						});
						this.dialogVisible = false;
						this.getListData();
					} else {
						uni.showToast({
							title: res.msg || (this.isEdit ? '更新失败' : '新增失败'),
							icon: 'none'
						});
					}
				} catch (error) {
					console.error(`${this.isEdit ? '更新' : '新增'}失败:`, error);
					uni.showToast({
						title: '网络错误，请稍后重试',
						icon: 'none'
					});
				} finally {
					this.loading = false;
					this.getListData();
				}
			},

			// 获取角色标签
			getRoleLabel(roleValue) {
				const role = this.roleOptions.find(item => item.value === roleValue);
				return role ? role.label : '未知角色';
			},
			// 获取门店名称
			getStoreName(storeId) {
				const store = this.storeOptions.find(item => item.value === storeId);
				return store ? store.label : storeId;
			}
		}
	};
</script>

<style scoped lang="scss">
	// 搜索输入框样式
	.search-input {
		width: 180px;
		height: 36px;
		line-height: 36px;
		background-color: #f5f7fa;
		border-radius: 4px;
		padding: 0 12px;
		font-size: 14px;
		border: 1px solid #eee;
	}

	// 列表增加用户名列样式
	.username-column {
		width: 20%;
	}

	.container {
		padding: 16px;
		background-color: #f5f7fa;
		min-height: 100vh;
	}

	.page-title {
		font-size: 24px;
		font-weight: bold;
		color: #333;
		margin-bottom: 20px;
		padding-bottom: 10px;
		border-bottom: 1px solid #eee;
	}

	// 搜索区域样式
	.search-container {
		display: flex;
		flex-wrap: wrap;
		gap: 12px;
		background-color: #fff;
		padding: 16px;
		border-radius: 8px;
		margin-bottom: 16px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

		.search-item {
			display: flex;
			align-items: center;
			gap: 8px;

			.label {
				font-size: 14px;
				color: #666;
				white-space: nowrap;
			}

			.picker,
			.search-input {
				width: 180px;
				height: 36px;
				line-height: 36px;
				background-color: #f5f7fa;
				border-radius: 4px;
				padding: 0 12px;
				font-size: 14px;
			}

			.search-input {
				border: 1px solid #ddd;
			}
		}

		.search-btn,
		.reset-btn,
		.add-btn {
			height: 36px;
			line-height: 36px;
			padding: 0 16px;
			border-radius: 4px;
			font-size: 14px;
			border: none;
			display: flex;
			align-items: center;
			justify-content: center;
		}

		.search-btn {
			background-color: #1677ff;
			color: #fff;
		}

		.reset-btn {
			background-color: #f5f7fa;
			color: #666;
		}

		.add-btn {
			background-color: #00b42a;
			color: #fff;
			margin-left: auto;
		}
	}

	// 列表区域样式
	.list-container {
		background-color: #fff;
		border-radius: 8px;
		overflow: hidden;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

		.list-header {
			display: flex;
			background-color: #f5f7fa;
			border-bottom: 1px solid #eee;
			font-weight: bold;
		}

		.list-body {
			max-height: calc(100vh - 320px);
			overflow-y: auto;
		}

		.list-row {
			display: flex;
			border-bottom: 1px solid #eee;
			transition: background-color 0.2s;

			&:last-child {
				border-bottom: none;
			}

			&:hover {
				background-color: #fafafa;
			}
		}

		.row-odd {
			background-color: #fcfcfc;
		}

		.list-item {
			padding: 12px;
			font-size: 14px;
			color: #333;
			display: flex;
			align-items: center;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
		}

		.id-column {
			width: 15%;
			/* 调整宽度 */
		}

		.userid-column {
			width: 15%;
			/* 调整宽度 */
		}

		.role-column {
			width: 12%;
			/* 调整宽度 */
		}

		.appid-column {
			width: 15%;
			/* 新增应用ID列宽度 */
		}

		.pmsid-column {
			width: 18%;
			/* 调整宽度 */
		}

		.operation-column {
			width: 20%;
			display: flex;
			gap: 8px;
			justify-content: center;

			.edit-btn,
			.delete-btn {
				padding: 4px 12px;
				font-size: 12px;
				border-radius: 4px;
				height: auto;
				line-height: normal;
			}

			.edit-btn {
				background-color: #ff7d00;
				color: #fff;
				border: none;
			}

			.delete-btn {
				background-color: #f53f3f;
				color: #fff;
				border: none;
			}
		}
	}

	// 空状态样式
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 40px 0;

		.empty-img {
			width: 120px;
			margin-bottom: 16px;
		}

		.empty-text {
			color: #999;
			font-size: 14px;
		}
	}

	// 加载状态样式
	.loading-state {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 40px 0;
		gap: 8px;

		.loading-text {
			color: #666;
			font-size: 14px;
		}
	}

	// 分页样式
	.pagination {
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 12px;
		margin-top: 20px;
		padding: 16px;

		.page-btn {
			padding: 6px 12px;
			background-color: #fff;
			border: 1px solid #eee;
			border-radius: 4px;
			font-size: 14px;
			color: #666;

			&:disabled {
				opacity: 0.6;
				cursor: not-allowed;
			}

			&:not(:disabled):hover {
				background-color: #f5f7fa;
			}
		}

		.page-info {
			font-size: 14px;
			color: #666;
		}
	}

	.store-column {
		width: 16%;
		/* 保持与原pmsid-column相同宽度 */
	}

	// 弹出框样式
	.modal-overlay {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 999;
		animation: fadeIn 0.3s;
	}

	.modal-container {
		width: 90%;
		max-width: 600px;
		background-color: #fff;
		border-radius: 10px;
		overflow: hidden;
		box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
		animation: slideIn 0.3s;
	}

	.modal-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 16px 20px;
		border-bottom: 1px solid #eee;

		.modal-title {
			font-size: 18px;
			font-weight: bold;
			color: #333;
		}

		.modal-close {
			background: transparent;
			border: none;
			font-size: 20px;
			color: #999;
			width: 30px;
			height: 30px;
			line-height: 30px;
			padding: 0;
			display: flex;
			align-items: center;
			justify-content: center;

			&:hover {
				color: #333;
			}
		}
	}

	.modal-body {
		padding: 20px;
	}

	.modal-footer {
		display: flex;
		justify-content: flex-end;
		gap: 12px;
		padding: 16px 20px;
		border-top: 1px solid #eee;
		background-color: #fafafa;
	}

	// 表单样式
	.form-item {
		display: flex;
		align-items: center;
		margin-bottom: 16px;
		gap: 12px;

		.form-label {
			width: 80px;
			font-size: 14px;
			color: #666;
			text-align: right;
		}

		.form-input,
		.form-picker {
			flex: 1;
			height: 36px;
			line-height: 36px;
			padding: 0 12px;
			border: 1px solid #ddd;
			border-radius: 4px;
			font-size: 14px;
		}

		.form-picker {
			display: flex;
			align-items: center;
			color: #333;
			background-color: #fff;
		}
	}

	// 按钮样式
	.clear-btn,
	.cancel-btn,
	.confirm-btn {
		padding: 8px 20px;
		border-radius: 4px;
		font-size: 14px;
		border: none;
	}

	.clear-btn {
		background-color: #722ed1;
		color: #fff;
	}

	.cancel-btn {
		background-color: #f5f7fa;
		color: #666;
	}

	.confirm-btn {
		background-color: #1677ff;
		color: #fff;
	}

	// 删除确认框样式
	.delete-modal {
		width: 90%;
		max-width: 400px;
		background-color: #fff;
		border-radius: 10px;
		overflow: hidden;
		box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
		animation: slideIn 0.3s;
	}

	.delete-title {
		font-size: 18px;
		font-weight: bold;
		color: #333;
		padding: 16px 20px;
		border-bottom: 1px solid #eee;
		text-align: center;
	}

	.delete-content {
		padding: 20px;
		color: #666;
		text-align: center;
		font-size: 14px;
	}

	.delete-footer {
		display: flex;
		justify-content: center;
		gap: 12px;
		padding: 16px 20px;
		border-top: 1px solid #eee;

		.delete-cancel,
		.delete-confirm {
			padding: 8px 20px;
			border-radius: 4px;
			font-size: 14px;
			border: none;
		}

		.delete-cancel {
			background-color: #f5f7fa;
			color: #666;
		}

		.delete-confirm {
			background-color: #f53f3f;
			color: #fff;
		}
	}

	// 动画
	@keyframes fadeIn {
		from {
			opacity: 0;
		}

		to {
			opacity: 1;
		}
	}

	@keyframes slideIn {
		from {
			transform: translateY(50px);
			opacity: 0;
		}

		to {
			transform: translateY(0);
			opacity: 1;
		}
	}
</style>